<template>
  <y-dialog @open="open" @close="emit('close')" width="1000px" append-to-body>
    <el-form
      ref="addRef"
      :model="form"
      :rules="rules"
      size="default"
      label-width="120px"
      label-position="top"
    >
      <el-row>
        <el-col>
          <el-form-item prop="content">
            <y-editor
              editorId="editorBugComment"
              v-model="form.content"
              placeholder="请输入评论信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="AuComment">
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["submited", "close"]);

const props = defineProps({
  id: { type: String, default: "" },
  operate: { type: String, default: "add" },
  getMethod: { type: Function, default: undefined },
  addMethod: { type: Function, default: undefined },
  updateMethod: { type: Function, default: undefined },
});

const data = reactive({
  form: {},
  rules: {
    comment: [{ required: true, message: "评论信息不能为空", trigger: "blur" }],
  },
});

const { form, rules } = toRefs(data);

/** 打开对话框事件 */
function open() {
  switch (props.operate) {
    case "update":
      props.getMethod(props.id).then((res) => {
        form.value = res.data;
      });
      break;
    default:
      break;
  }
}

/** 提交按钮事件 */
function submit() {
  proxy.$refs["addRef"].validate((valid) => {
    if (valid) {
      useUserStore()
        .getInfo()
        .then((res) => {
          if (form.value.id != undefined) {
            props.updateMethod(form.value).then((res) => {
              proxy.$modal.msgSuccess("修改成功");
              submited();
            });
          } else {
            form.value.bug = props.id;
            form.value.creator = res.data.user.id;
            props.addMethod(form.value).then((res) => {
              proxy.$modal.msgSuccess("新增成功");
              submited();
            });
          }
        });
    }
  });
}

/** submited事件 */
function submited() {
  emit("submited");
  emit("close");
}
</script>
